﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LexLib.LexemNameSpace;
using System.Threading;
using TextEditor4.Parser;
using LexLib.LexerNameSpace;
using System.Diagnostics;
using System.Windows;
using TextEditor4.Refactoring;
using System.IO;
//using System.Windows.Media;


namespace TextEditor4
{
    public partial class Form1 : Form
    {
        Lexer myLex = new Lexer();
        static string str;
        TextEditor4.Parser.IParseNodeType parseTree;
        private bool m_DocumentChanged = false;
        public int curs;
        public int[] tmpP;
        public int[] coordP;
        public string DocName = "Untitled.txt";
        

        bool changed = false;
        string fpath;



        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerSupportsCancellation = true;
            richTextBox1.SelectionColor = Color.Black;
            undoToolStripMenuItem.Enabled = false;
            redoToolStripMenuItem.Enabled = false;
            Redo.Enabled = false;
            Undo.Enabled = false;
            this.Text = "File [" + "Untitled.txt" + "]";
        }

        /// <summary>
        /// Запускает лексер при вводе любого символа в поле RTB
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void rtbTextChanged(object sender, System.EventArgs e)
        {
            undoToolStripMenuItem.Enabled = true;
            Undo.Enabled = true;
        }

        /// <summary>
        /// метод, который по нажатию кнопки будет находить и красить все вхождения слова "war"
        /// </summary>


        private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
        {
            //string time1 = " ";
            //Stopwatch myWatch = new Stopwatch();
            //myWatch.Start();
            
            m_DocumentChanged = true;
            undoToolStripMenuItem.Enabled = true;
            Undo.Enabled = true;
            //while (backgroundWorker1.IsBusy)
            //{
            //    backgroundWorker1.CancelAsync();
            //}
            curs = richTextBox1.SelectionStart;
            Keys kd = e.KeyCode;
            if (e.Control)
            {
                switch (kd)
                {
                    case Keys.S:
                        {
                            saveToolStripMenuItem_Click(null, null);
                            break;
                        }
                    case Keys.O:
                        {
                            openToolStripMenuItem_Click(null, null);
                            break;
                        }
                }
            }
            else
            {
                if (((kd <= Keys.Z) && (kd >= Keys.A)) || ((kd >= Keys.D0) && (kd <= Keys.D9))
                    || (kd == Keys.OemMinus) || (kd == Keys.Oemplus) || (kd == Keys.OemOpenBrackets)
                    || (kd == Keys.OemCloseBrackets) || (kd == Keys.OemSemicolon)
                    || (kd == Keys.OemQuotes) || (kd == Keys.OemQuestion) || (kd == Keys.OemPipe)
                    || (kd == Keys.OemPeriod) || (kd == Keys.Oemcomma)
                    || (kd == Keys.Delete) || (kd == Keys.Back)
                    || (kd == Keys.Space))
                {
                    richTextBox1.Font = new System.Drawing.Font(richTextBox1.Font, new System.Drawing.FontStyle());
                    str = richTextBox1.Text;
                    //time1 = str.Length.ToString();
                    try
                    {
                        backgroundWorker1.CancelAsync();
                        backgroundWorker1.RunWorkerAsync(str);
                     }
                    catch (Exception c) { }
                    
                }
            }
        }

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {


        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_DocumentChanged)
            {
                DialogResult result = MessageBox.Show("The document was changed.Save changes?", "Сохранение документа", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                switch (result)
                {
                    case DialogResult.Yes:
                        {
                            MenuSaveAs();
                            break;
                        }
                    case DialogResult.Cancel:
                        {
                            return;
                        }
                }
            }


            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK && openFileDialog1.FileName.Length > 0)
            {
                try
                {
                    richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText);
                }
                catch (System.ArgumentException ex)
                {
                    richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
                }
                DocName = openFileDialog1.FileName;
                this.Text = "File [" + DocName + "]";

            }
            m_DocumentChanged = false;
            richTextBox1_KeyUp(sender, new KeyEventArgs(Keys.Space));
            //tmp();
        }


        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "Text Files (*.txt)|*.txt|TE4 Files (*.tf)|*.tf|All Files(*.*)|*.*";
            saveFileDialog1.ShowDialog();
            string fileName = saveFileDialog1.FileName;
            if (fileName == "")
            {
                return;
            }
            else
            {
                try
                {
                    //создаем поток и откр.File для записи
                    System.IO.FileStream filestream = System.IO.File.Open(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                    if (filestream != null)
                    {
                        //связываем с потоком объект
                        System.IO.StreamWriter streamwriter = new System.IO.StreamWriter(filestream);
                        //пишем данные в File
                        streamwriter.Write(richTextBox1.Text);
                        //переносим данные из потока в File
                        streamwriter.Flush();
                        filestream.Close();

                    }
                }
                catch (Exception ex) { }
                m_DocumentChanged = false;
                DocName = fileName;
                this.Text = "File [" + DocName + "]";
            }

        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }


        /// <summary>
        /// рефакторилка
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            myLex.ArrOfLexems[0] = new Lexem(new ProgramType(), 0, myLex.ArrOfLexems[myLex.ArrOfLexems.Count - 1].EndIndex);
            Parser.Parser myP = new Parser.Parser(myLex.ArrOfLexems);
            TextEditor4.Parser.IParseNodeType tmp = myP.parse();
            int varNum = richTextBox1.SelectionStart;
            Refactoring.Refactoring myR = new Refactoring.Refactoring(tmp, varNum);
            IParseNodeType refactedTree = myR.Refactor(tmp);
            List<int> myrefList = myR.refPositions;
            myrefList.Reverse();
            changeNames(myrefList, getSize(varNum), "Foo");
        }

        private void changeNames(List<int> placesToChange, int oldSize, string newName)
        {
            foreach (int i in placesToChange)
            {
                richTextBox1.Select(i, oldSize);
                richTextBox1.SelectedText = newName;
            }
        }
        private int getSize(int position)
        {
            for (int i = 1; i < myLex.ArrOfLexems.Count; i++)
            {
                if ((myLex.ArrOfLexems[i].BeginIndex <= position) && (myLex.ArrOfLexems[i].EndIndex >= position))
                {
                    return (myLex.ArrOfLexems[i].EndIndex - myLex.ArrOfLexems[i].BeginIndex);
                }
            }
            return 0;
        }

        private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string s = richTextBox1.SelectedText;
            Rename_Form renamefrm = new Rename_Form(myLex, richTextBox1, s);
            renamefrm.ShowDialog();
            tmp();
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!File.Exists("KeyWordRedactor.exe"))
            {
                keyWordsToolStripMenuItem.Enabled = false;
            }
        }

        private void parseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            myLex.ArrOfLexems[0] = new Lexem(new ProgramType(), 0, myLex.ArrOfLexems[myLex.ArrOfLexems.Count - 1].EndIndex);
            Parser.Parser myP = new Parser.Parser(myLex.ArrOfLexems);
            try
            {
                TextEditor4.Parser.IParseNodeType tmp = myP.parse();
                ExceptionForm myEF = new ExceptionForm("There are no exceptions in code", "No exceptions");
                myEF.Show();
            }
            catch (ParseException ex)
            {
                ExceptionForm myEF = new ExceptionForm(ex.Description);
                myEF.Show();
                richTextBox1.Select(ex.ExceptionPosition, ex.ExceptionPositionEnd - ex.ExceptionPosition);
                System.Drawing.FontStyle newFS;
                newFS = System.Drawing.FontStyle.Underline;
                richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, richTextBox1.SelectionFont.Size, newFS);


                richTextBox1.SelectionLength = 0;
                richTextBox1.SelectionColor = Color.Black;
            }

        }
        private void Form1_Activated(object sender, EventArgs e)
        {
            //myLex = new Lexer();
        }

        private int[] tmpParse()
        {
            try
            {
                myLex.ArrOfLexems[0] = new Lexem(new ProgramType(), 0, myLex.ArrOfLexems[myLex.ArrOfLexems.Count - 1].EndIndex);
                Parser.Parser myP = new Parser.Parser(myLex.ArrOfLexems);
                try
                {
                    parseTree = myP.parse();
                    return null;
                }
                catch (ParseException ex)
                {
                    int[] tmp = new int[2];
                    tmp[0] = ex.ExceptionPosition;
                    tmp[1] = ex.ExceptionPositionEnd;
                    return tmp;
                }
            }
            catch (Exception ex)
            { return null; }

        }

        private void keyWordsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("KeyWordRedactor.exe");
        }


        private void MenuSaveAs()
        {
            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK && saveFileDialog1.FileName.Length > 0)
            {
                richTextBox1.SaveFile(saveFileDialog1.FileName);
                DocName = saveFileDialog1.FileName;
                this.Text = "File [" + DocName + "]";
                m_DocumentChanged = false;

            }
        }



        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_DocumentChanged)
            {
                DialogResult result = MessageBox.Show(
                  "The document was changed.Save changes?",
                  "Сохранение документа", MessageBoxButtons.YesNoCancel,
                  MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);

                switch (result)
                {
                    case DialogResult.Yes:
                        {
                            MenuSaveAs();
                            break;
                        }
                    case DialogResult.Cancel:
                        {
                            return;
                        }
                }
            }
            DocName = "Untitled.txt";
            this.Text = "File [" + DocName + "]";
            richTextBox1.Clear();
            m_DocumentChanged = false;

        }


        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_DocumentChanged)
            {
                DialogResult result = MessageBox.Show(
                  "Save changes to the document before closing?",
                  "Сохранение документа", MessageBoxButtons.YesNoCancel,
                  MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);

                switch (result)
                {
                    case DialogResult.Yes:
                        {
                            MenuSaveAs();
                            break;
                        }
                    case DialogResult.Cancel:
                        {
                            return;
                        }
                }
            }
            this.Close();
        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.SelectAll();
        }

        private void copyToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }

        private void pasteToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }

        private void cutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        private void tmp()
        {
            int j = richTextBox1.SelectionStart;
            str = richTextBox1.Text;
            myLex.automat(str);
            List<Lexem> lexems = myLex.ArrOfLexems;
            for (int i = lexems.Count - 1; i >= 0; i--)
            {
                Lexem lex = lexems[i];
                string cl = lex.TypeOfLexem.GetColor;
                str.Insert(lex.EndIndex, cl);
                str.Insert(lex.BeginIndex, cl);
            }
            richTextBox1.SelectionStart = j;

            richTextBox1.ForeColor = Color.Black;
        }

        private void renameMyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                int num = richTextBox1.SelectionStart;
                string s = richTextBox1.SelectedText;
                if (!Char.IsLetterOrDigit(richTextBox1.Text[num]))
                {

                    ExceptionForm myEF = new ExceptionForm("You havn't choose the variable to rename");
                    myEF.Show();
                }
                else
                {
                    renameMyToolStripMenuItem.Enabled = true;
                    Rename_Form renamefrm = new Rename_Form(myLex, richTextBox1, s);
                    renamefrm.ShowDialog();
                    tmp();
                }
            }
            catch (Exception ex)
            {
                ExceptionForm myEF = new ExceptionForm("Incorrect input");
                myEF.Show();
            }
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //str = (string)e.Argument;
            myLex.automat((string)e.Argument);
            string strtemp = (string)e.Argument;
            string strt = strtemp;
            StringBuilder mySB = new StringBuilder();
            mySB.Append("{\\rtf1{\\colortbl;\\red0\\green0\\blue0;\\red0\\green0\\blue255;\\red0\\green255\\blue0;\\red150\\green75\\blue0;\\red0\\green255\\blue0;\\red255\\green0\\blue0;}");
            List<Lexem> lexems = myLex.ArrOfLexems;
            int jj = 0;
            for (int i = 0; i <= lexems.Count - 1; i++)
            {
                if (backgroundWorker1.CancellationPending) { e.Cancel = true; return; }
                else
                {
                    Lexem lex = lexems[i];
                    string cl = lex.TypeOfLexem.GetColor;
                    string temp = strtemp.Substring(jj, lex.beginIndex - jj);
                    temp = temp.Replace("\n", "\\par");
                    mySB.Append(temp);
                    //str = str.Insert(lex.BeginIndex, cl);
                    if (lex.TypeOfLexem is OpenFigureBracketType)
                    {
                        mySB.Append(cl);
                        mySB.Append("\\{");
                    }
                    else
                    {
                        if (lex.TypeOfLexem is CloseFigureBracketType)
                        {
                            mySB.Append(cl);
                            mySB.Append("\\}");
                        }
                        else
                        {
                            mySB.Append(cl);
                            mySB.Append(strtemp.Substring(lex.beginIndex, lex.endIndex - lex.beginIndex));
                            mySB.Append("}");
                        }
                    }
                    jj = lex.endIndex;
                }
                        
            }
            string temp1 = strtemp.Substring(jj,strtemp.Length - jj);
            temp1 = temp1.Replace("\n", "\\par");
            mySB.Append(temp1);
            mySB.Append("}");
            strtemp = mySB.ToString();
            tmpP = tmpParse();
            if (backgroundWorker1.CancellationPending) { e.Cancel = true; return; } else { e.Result = strtemp; }
        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //Stopwatch myWatch = new Stopwatch();            
            //string strtemp = richTextBox1.Text;
            //int count = strtemp.Length;
            //myWatch.Start();
            
            if (e.Cancelled != true)
            {
                string strtemp = (string) e.Result;
                richTextBox1.Rtf = strtemp;
                if (tmpP != null)
                {
                    richTextBox1.SelectionStart = tmpP[0];
                    richTextBox1.SelectionLength = tmpP[1] - tmpP[0];
                    System.Drawing.FontStyle newFS;
                    newFS = System.Drawing.FontStyle.Underline;
                    System.Drawing.Font oldFS = richTextBox1.SelectionFont;
                    richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, richTextBox1.SelectionFont.Size, newFS);
                    richTextBox1.SelectionLength = 0;

                    richTextBox1.DeselectAll();
                    richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, new System.Drawing.FontStyle());
                }
                richTextBox1.SelectionStart = curs;
                richTextBox1.ForeColor = Color.Black;
                //myWatch.Stop();
                //string time2 = myWatch.ElapsedMilliseconds.ToString() + " ms";
                //if (time2!="0 ms") {
                //FileStream fs2 = new FileStream("threads.txt", FileMode.Append);
                //BinaryWriter bw = new BinaryWriter(fs2);
                //bw.Write(count + "symb " + time2);
                //fs2.Close();}
            }
        }
        private int redoCount = 0;
        private void undoToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            int i = 100;
            if ((redoCount >= 0) && (richTextBox1.Text.Length != 0))
            {
                redoCount++;
                int lenght = richTextBox1.Text.Length;
                while ((i > 0) && (lenght == richTextBox1.Text.Length))
                {
                    richTextBox1.Undo();
                    i--;
                }
                redoToolStripMenuItem.Enabled = true;
                Redo.Enabled = true;
            }

            else
            {
                undoToolStripMenuItem.Enabled = false;
                Undo.Enabled = false;
            }
        }

        private void redoToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            if (redoCount > 0)
            {
                int lenght = richTextBox1.Text.Length;
                while (lenght == richTextBox1.Text.Length)
                {
                    richTextBox1.Redo();
                }
                redoCount--;
            }
            else
            {
                redoToolStripMenuItem.Enabled = false;
                Redo.Enabled = false;
            }
        }


        private void New_Click_1(object sender, EventArgs e)
        {
            if (m_DocumentChanged)
                MenuSaveAs();
            richTextBox1.Clear();
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            m_DocumentChanged = true;
        }

        private void Open_Click_1(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Text Files (*.txt)|*.txt|TE4 Files (*.tf)|*.tf|All Files(*.*)|*.*";
            //Открываем(показ-м) диалог менюшки
            openFileDialog1.ShowDialog();
            //задаем переменную FileName(имя открыв.Fileа)
            string fileName = openFileDialog1.FileName;
            if (fileName == "")
            {
                return;
            }
            else
            {
                try
                {
                    //создаем поток Filestream и открыв.File
                    System.IO.FileStream filestream = System.IO.File.Open(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    //если поток не пуст
                    if (filestream != null)
                    {
                        System.IO.StreamReader streamreader = new System.IO.StreamReader(filestream);
                        //Читаем File и записываем его в rich..
                        richTextBox1.Text = streamreader.ReadToEnd();
                        //закрываем поток
                        filestream.Close();

                    }
                }
                catch (Exception ex) { }
            }
            richTextBox1_KeyUp(sender, new KeyEventArgs(Keys.Space));
            //tmp();
        }

        private void SaveAs_Click_1(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "Text Files (*.txt)|*.txt|TE4 Files (*.tf)|*.tf|All Files(*.*)|*.*";
            saveFileDialog1.ShowDialog();
            string fileName = saveFileDialog1.FileName;
            if (fileName == "")
            {
                return;
            }
            else
            {
                try
                {
                    //создаем поток и откр.File для записи
                    System.IO.FileStream filestream = System.IO.File.Open(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                    if (filestream != null)
                    {
                        //связываем с потоком объект
                        System.IO.StreamWriter streamwriter = new System.IO.StreamWriter(filestream);
                        //пишем данные в File
                        streamwriter.Write(richTextBox1.Text);
                        //переносим данные из потока в File
                        streamwriter.Flush();
                        filestream.Close();

                    }
                }
                catch (Exception ex) { }
            }

        }

        private void Cut_Click_1(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        private void Copy_Click_1(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }

        private void Paste_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }

        private void Undo_Click(object sender, EventArgs e)
        {
            int i = 100;
            if ((redoCount >= 0) && (richTextBox1.Text.Length != 0))
            {
                redoCount++;
                int lenght = richTextBox1.Text.Length;
                while ((i > 0) && (lenght == richTextBox1.Text.Length))
                {
                    richTextBox1.Undo();
                    i--;
                }
                redoToolStripMenuItem.Enabled = true;
                Redo.Enabled = true;
            }

            else
            {
                undoToolStripMenuItem.Enabled = false;
                Undo.Enabled = false;
            }
        }

        private void Redo_Click(object sender, EventArgs e)
        {
            if (redoCount > 0)
            {
                int lenght = richTextBox1.Text.Length;
                while (lenght == richTextBox1.Text.Length)
                {
                    richTextBox1.Redo();
                }
                redoCount--;
            }
            else
            {
                redoToolStripMenuItem.Enabled = false;
                Redo.Enabled = false;
            }
        }


        private void refactoringToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }


        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            int tmp = richTextBox1.SelectionStart;
            try
            {
                if (Char.IsLetterOrDigit(richTextBox1.Text[richTextBox1.SelectionStart]))
                {
                    renameMyToolStripMenuItem.Enabled = true;
                }
                else
                {
                    renameMyToolStripMenuItem.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                renameMyToolStripMenuItem.Enabled = false;
            }
        }

        private void Undo_Click_1(object sender, EventArgs e)
        {
            int i = 100;
            if ((redoCount >= 0) && (richTextBox1.Text.Length != 0))
            {
                redoCount++;
                int lenght = richTextBox1.Text.Length;
                while ((i > 0) && (lenght == richTextBox1.Text.Length))
                {
                    richTextBox1.Undo();
                    i--;
                }
                redoToolStripMenuItem.Enabled = true;
                Redo.Enabled = true;
            }

            else
            {
                undoToolStripMenuItem.Enabled = false;
                Undo.Enabled = false;
            }
        }

        private void Redo_Click_1(object sender, EventArgs e)
        {
            if (redoCount > 0)
            {
                int lenght = richTextBox1.Text.Length;
                while (lenght == richTextBox1.Text.Length)
                {
                    richTextBox1.Redo();
                }
                redoCount--;
            }
            else
            {
                redoToolStripMenuItem.Enabled = false;
                Redo.Enabled = false;

            }
        }

        private void helpToolStripMenuItem1_Click_1(object sender, EventArgs e)
        {
            //Help myH = new Help();
            //myH.Show();
            Process.Start("TE4Help.chm");
        }

        private void AboutToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            About myA = new About();
            myA.Show();
        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void saveToolStripMenuItem1_Click_1(object sender, EventArgs e)
        {
            Save(DocName);
        }

        public void Save(string SaveFileName)
        {
            if (SaveFileName == "")
            {
                return;
            }
            else
            {
                try
                {
                    //Создаем новый объект StreamWriter и передаем ему переменную OpenFileName
                    FileStream fs = new FileStream(SaveFileName, FileMode.OpenOrCreate, FileAccess.Write);
                    BinaryWriter bw = new BinaryWriter(fs);
                    if (SaveFileName.Contains(".txt"))
                    {
                        bw.Write(richTextBox1.Text);
                    }
                    else
                    {
                        bw.Write(richTextBox1.Rtf);
                    }
                    //StreamWriter sw = new StreamWriter(SaveFileName);
                    //Содержимое richTextBox1 записываем в File
                    //sw.WriteLine(richTextBox1.Text);
                    //Закрываем поток
                    //sw.Close();
                    fs.Close();
                    //Устанавливаем в качестве имени документа название сохраненного Fileа
                    DocName = SaveFileName;
                }
                catch (Exception ex) { }
            }
        }
    }
}
